package com.shushan.pages;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.exam.OnResultCollectListener;
import com.shushan.exam.bean.ExerciseBean;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.UserBean;
import com.shushan.mixedexam.MixedExamActivity;
import com.shushan.mixedexam.bean.ExerciseResultBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.bean.ExerciseRecordDetailsBean;
import com.shushan.pages.bean.MaketingDataBean;
import com.shushan.pages.bean.PaperInfoBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;
import com.shushan.web.GoodsDetailWebActivity;


/**
 * @ClassName: NewRecordResultActivity
 * @Desciption: //新版练习记录结果页
 * @author: zhangshihao
 * @date: 2018-05-12
 */
public class NewRecordResultActivity extends BaseActivity implements View.OnClickListener, OnResultCollectListener {

    private static final String TAG = "NewRecordResultActivity";

    private ImageView backImageView;
    private TextView getTimeText;
    private Button btnWatchTopic, btnContinueExercise;
    private ImageView btnExamAgain;
    private ImageView ivExerciseContinue, ivUseNow, ivWatchWrongTopic, ivExchangeReward, ivGetToyNow;
    private RelativeLayout rlGetToyLayout, rlFutureToyLayout;
    private TextView tvWrongTopicNum;
    private TextView tvExerciseCountRest, tvFutureToyName;
    private TextView tvRewardStarNum;
    private ImageView ivGetSystemToyNow;
    private TextView tvExamScore;
    private TextView tvRewardTimeDesc;

    private ExerciseRecordDetailsBean paperBean;

    private int paperId = 0;
    private String create_time;
    private int practiceType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScreenManager.getInstance().setStatusBar(true, this);
        setContentView(R.layout.activity_record_result_new);

        Intent intent = getIntent();
        paperId = intent.getIntExtra("paper_id", 0);
        create_time = intent.getStringExtra("create_time");
        practiceType = intent.getIntExtra("practice_type",0);

        initView();

        getData();
    }

    private void initView() {
        getTimeText = findViewById(R.id.tv_get_time);
        backImageView = findViewById(R.id.top_left_back_img);
        backImageView.setOnClickListener(this);
        btnWatchTopic = findViewById(R.id.btn_watch_topic);
        btnWatchTopic.setOnClickListener(this);
        btnExamAgain = findViewById(R.id.btn_exam_again);
        btnExamAgain.setOnClickListener(this);
        ivExerciseContinue = findViewById(R.id.iv_exercise_continue);
        ivExerciseContinue.setOnClickListener(this);
        ivUseNow = findViewById(R.id.iv_use_now);
        ivUseNow.setOnClickListener(this);
        ivWatchWrongTopic = findViewById(R.id.iv_watch_wrong_topic);
        ivWatchWrongTopic.setOnClickListener(this);
        ivExchangeReward = findViewById(R.id.iv_exchange_reward);
        ivExchangeReward.setOnClickListener(this);
        ivGetToyNow = findViewById(R.id.iv_get_now);
        ivGetToyNow.setOnClickListener(this);
        rlGetToyLayout = findViewById(R.id.rl_get_toy_layout);
        rlFutureToyLayout = findViewById(R.id.rl_future_toy_layout);
        tvWrongTopicNum = findViewById(R.id.tv_wrong_topic_num);
        tvExerciseCountRest = findViewById(R.id.tv_exercise_count_rest);
        tvFutureToyName = findViewById(R.id.tv_future_toy_name);
        tvRewardStarNum = findViewById(R.id.tv_reward_star_num);
        btnExamAgain = findViewById(R.id.btn_exam_again);
        btnExamAgain.setOnClickListener(this);
        btnContinueExercise = findViewById(R.id.btn_continue_exercise);
        btnContinueExercise.setOnClickListener(this);
        ivGetSystemToyNow = findViewById(R.id.iv_get_system_toy_now);
        ivGetSystemToyNow.setOnClickListener(this);
        tvExamScore = findViewById(R.id.tv_exam_score);
        tvRewardTimeDesc = findViewById(R.id.tv_reward_time_desc);
    }

    private void getData() {
        int child_id = BabyApplication.getInstance().getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.EXERCISE_DETAILS_NEW);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", child_id)
                .putValue("paper_id", paperId);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<ExerciseRecordDetailsBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(ExerciseRecordDetailsBean exerciseRecordDetailsBean) {
                        if(exerciseRecordDetailsBean == null){
                            return;
                        }
                        paperBean = exerciseRecordDetailsBean;
                        initData(exerciseRecordDetailsBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void initData(ExerciseRecordDetailsBean exerciseRecordDetailsBean) {
        PaperInfoBean paperInfoBean = exerciseRecordDetailsBean.paperInfoBean;
        ExerciseResultBean resultBean = paperInfoBean.exerciseResultBean;

        int chineseScore = resultBean.chineseScore;
        int mathScore = resultBean.mathScore;
        int englishScore = resultBean.englishScore;
        int subCount = 3;
        if(chineseScore < 0){
            chineseScore = 0;
            subCount--;
        }
        if(mathScore < 0){
            mathScore = 0;
            subCount--;
        }
        if(englishScore < 0){
            englishScore = 0;
            subCount--;
        }
        int score;
        if(practiceType == Constants.TYPE_SYNC_EXERCISE){
            if(subCount == 0){
                score = 0;
            }else {
                score = (chineseScore + mathScore + englishScore) / subCount;
            }
        }else if (practiceType == Constants.TYPE_SMART_EXERCISE){
            score = resultBean.score;
        } else{
            score = chineseScore+mathScore+englishScore;
        }
        tvExamScore.setText(score+"分");

        tvRewardStarNum.setText(resultBean.stars_num+"");
        getTimeText.setText(resultBean.reward_time+"");
        if(resultBean.reward_time == 0){
            tvRewardTimeDesc.setVisibility(View.VISIBLE);
            tvRewardTimeDesc.setText(resultBean.reward_description);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_watch_topic://查看习题
                if(paperBean != null){
                    Session.getSession().put("paperBean", paperBean);

                    Intent intent = new Intent(this,RecordDetailActivity.class);
                    intent.putExtra("practiceType",practiceType);
                    startActivityAllow(intent);
                }else {
                    showToast("数据为空");
                    return;
                }
                break;
            case R.id.btn_exam_again://重考
                examAgain();
                break;
            case R.id.iv_exercise_continue://继续练习
            case R.id.btn_continue_exercise://继续练习
                onBackAction();
                break;
            case R.id.iv_use_now://立即使用手机
                break;
            case R.id.iv_watch_wrong_topic://查看错题
                Session.getSession().put("paperBean",paperBean);

                Intent intent2 = new Intent(this,RecordDetailActivity.class);
                intent2.putExtra("isWatchWrongTopic",true);
                intent2.putExtra("practiceType",practiceType);
                startActivityAllow(intent2);
                break;
            case R.id.iv_exchange_reward://兑换奖品
                startActivity(MyStarActivity.class);
                break;
            case R.id.top_left_back_img:
                onBackAction();
                break;
            case R.id.iv_get_system_toy_now:
                gotoToyWeb();
                break;
            default:
                break;
        }
    }

    private void gotoToyWeb() {
        ChildBean currentChildBean = BabyApplication.getInstance().getCurrentChildBean();
        UserBean currentUserBean = BabyApplication.getInstance().getUserBean();
        int childId = currentChildBean.id;
        UrlParse urlParse = new UrlParse(UrlConst.BASE_URL)
                .appendRegion(UrlConst.DIST_TOY_HTML)
                .putValue("phone", SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))
                .putValue("childid", (childId > 0) ? (childId+"") : "")
                .putValue("starsnum",currentChildBean.stars)
                .putValue("goodsid",0)
                .putValue("viptype", ToolUtils.getVipTypeForGoodsDetails(currentUserBean))
                ;

        Intent intent = new Intent(this, GoodsDetailWebActivity.class);
        intent.putExtra("title","奖品详情");
        intent.putExtra("url",urlParse.toString());
        startActivityForResultAllow(intent,100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 200){//领取奖励成功
            showToast("领取成功");
        }else if(resultCode == 500){//玩具详情点击购买
            startActivity(OpenVipSpendActivity.class);
        }
    }

    private void getMaketingData(){
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.MEMBER_CENTER);
        UrlParse paramParse = new UrlCommParse(this).putValue("phone",SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<MaketingDataBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(MaketingDataBean maketingDataBean) {
                        Session.getSession().put("maketingDataBean",maketingDataBean);

                        startActivity(OpenVipActivity.class);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void examAgain() {
        onBackAction();

        Session.getSession().put("paperBean", paperBean);

        Intent intent = new Intent(NewRecordResultActivity.this, MixedExamActivity.class);
        intent.putExtra("examType",Constants.TYPE_SYNC_EXERCISE);
        intent.putExtra("fromResultType",0);
        startActivityAllow(intent);
    }

    /**
     * 收藏和取消收藏
     *
     * @param collectType 1:收藏试题2:取消收藏试题
     */
    private void doPostCollect(final int collectType, final ExerciseBean exerciseBean) {
        int childId = BabyApplication.getInstance().getCurrentChildId();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.TOPIC_COLLECT);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id", childId)
                .putValue("exercise_id", exerciseBean.id)
                .putValue("subject_id", exerciseBean.subject_id)
                .putValue("exercises_type", practiceType)
                .putValue("type", collectType + "");

        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        if (exerciseBean.child_collect == 1) {
                            exerciseBean.child_collect = 0;
                        } else {
                            exerciseBean.child_collect = 1;
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onResultCollect(ExerciseBean exerciseBean) {
        if (exerciseBean == null) {
            return;
        }

        if (exerciseBean.child_collect == 0) {
            doPostCollect(1, exerciseBean);
        } else {
            doPostCollect(2, exerciseBean);
        }
    }

}
